<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');

class tool extends CI_Controller {

	function __construct() {

		parent::__construct();
	}

	public function field($table_name = '', $return = false) {
		$fields = $this->db->field_data($table_name);

		$result = '';
		$result.= '$fieldData = array();';
		$result.= "\n";
		foreach ($fields as $field) {
			if ($field->primary_key == 1)
				continue;
			if ($field->default == '')
				$data = $this->fieldDefault($field->name, $field->type);
			else
				$data = $field->default;
			$result.= '$fieldData[\'' . $field->name . '\'] = ' . $data . ';';
			$result.= "\n";
		}
		$result.= 'return $fieldData;';
		if ($return)
			return $result;
		echo $result;
	}

	public function model_generator($table_name) {
		
		$dir = APPPATH ."models/";
		$template_model = file_get_contents($dir . "template_model.tmp");

		$file_name = 'm' . str_replace('_', '', $table_name);
		$fullpath = $dir. $file_name . EXT;
		if (file_exists($fullpath)) {
			echo "exists &nbsp;| " .$fullpath ."\n<br />";
			die;
		}
		echo "writing | " . $fullpath.  "\n<br />" ;
		$data = array(
			'{CLASSNAME}' => $file_name,
			'{TABLE_NAME}' => $table_name,
			'{CODE}' => strtoupper($table_name),
			'{PRIMARY_KEY}' => $this->get_primary($table_name),
			'{FIELD}' => $this->field($table_name, true)
		);

		$model_content = str_replace(
				array_keys($data), array_values($data), $template_model);
		file_put_contents($fullpath, $model_content);
			
	}

	function get_primary($table_name) {
		$fields = $this->db->field_data($table_name);
		foreach ($fields as $field) {
			if ($field->primary_key == 1)
				return $field->name;
		}
	}

	function fieldDefault($name, $type = '') {
		$default = "";

		//time
		if (strpos($name, "TIME_"))
			$default = 'time()';
		else if (strpos($name, "_STATUS"))
			$default = '1';
		else if ($type == 'bigint' || $type == 'int')
			$default = '0';
		else
			$default = "''";
		return $default;
	}

	function scandir() {
		$filess = scandir('./template/admin/js/');
		foreach ($filess as $files) {
			echo '\$this->template->add_css_lib("' . $files . '");';
		}
	}
	function build_link_cache(){
		$this->load->helper('file');
		$this->load->model("mcategory");
		$cates = $this->mcategory->gets();
		$data_temp =array();
		$data = "<?php \n";
        $data.="return ";
		if($cates) {
			foreach($cates as $cate){
			if($cate->cat_code != '')
				$data_temp[] = strtolower($cate->cat_code);
			}
		$data_temp = var_export($data_temp, true);
		$data.= $data_temp;
        $data.="?>\n";
        write_file('./mcache/category_router.php', $data);
		}
		
	}
	
	function cat_code(){
	$this->load->model("mcategory");
	echo '<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />';
		$cates = $this->mcategory->gets();
	
		foreach($cates as $cate){
			$arr_update = array();
			//$arr_update['cat_code'] = $this->sseo->seolink($cate->cat_name);
			$arr_update['seo_title'] = $cate->cat_name;
			$this->mcategory->update($cate->cat_id,'cat_id',$arr_update);
		}
	//$this->build_link_cache();
	}
	
	function import_data() {
	
		$this->load->library('excel');
		$this->load->model('mgame');
		$i = 0;
		$file = './dataupload/gamedb1.xlsx';
		//sleep(99999999999999);

		$inputFileType = PHPExcel_IOFactory::identify($file);
		$objReader = PHPExcel_IOFactory::createReader($inputFileType);
		$objPHPExcel = $objReader->load($file);
		$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
		$arr_insert = array();
		unset($sheetData[1]);
		echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
		foreach ($sheetData as $data) {
			$arr_insert = array();
			if(trim($data['C']) == '') {
				echo "title: Null <br>";
				continue;
			}
			$this->db->where("game_title",$data['C']);
			$check = $this->mgame->get($data['H'],'game_key');
			if($check) {
			echo "title: ".$data['C'].", key".$data['H']." exists<br>";
			continue;
			}
			
			$cat_id = $data['B'];
			$cat_id = explode(",",$cat_id);
			if(count($cat_id) == 0){
				echo "Game ".$data['C']." not catid<br>";
				//echo "\rGame ".$data['B']." not catid";
				continue;
			}
			
			$arr_insert['game_title'] = trim($data['C']);
			$arr_insert['game_code'] =  $this->sseo->seolink($arr_insert['game_title']);
			$arr_insert['game_time_create'] = time();
			$arr_insert['game_time_update'] = time();
			$arr_insert['game_content'] = $data['D'];
			$arr_insert['game_thumb'] = 'dataupload/game/thumb/'.trim($data['E']);
			$arr_insert['game_file'] = 'dataupload/game/data/'.trim($data['F']);
			$arr_insert['game_key'] = trim($data['H']);
			$arr_insert['seo_h1'] = $arr_insert['game_title'];
			$arr_insert['seo_title'] = $arr_insert['game_title'];
			if($data['H'] =="-1")
				$arr_insert['game_status'] = 1;
			else 
				$arr_insert['game_status'] = 2;
				
			$this->db->insert("game",$arr_insert);
			//$game_id = $this->mgame->insert($arr_insert);
			$game_id = $this->db->insert_id();
			echo "imported ".$arr_insert['game_title']."<br>";
			$arr_insert = array();
			$cat_id = array_keys(array_flip($cat_id)); 
			foreach($cat_id as $cat){
				if($cat >0){
					$arr_insert['cat_id'] = $cat;
					$arr_insert['game_id']= $game_id;
					$this->db->insert("game_category",$arr_insert);
				}
			}
			
			$arr_insert = array();
			$huong_dan = $data['G'];
			$huong_dan =str_replace("\n","",$huong_dan);
			$huong_dan = explode("|",$huong_dan);
			//$huong_dan = array_keys(array_flip($huong_dan)); 
			foreach($huong_dan as $hd){
				if($hd !=''){
				$hd =str_replace("\n","",$hd);
				$hds = explode(":",trim($hd));
				//$hd_key = str_replace(",","",trim($hd_key));
				$hds[0] = trim($hds[0]);
				$hds[1] = trim($hds[1]);
				if($hds[0] =='' || $hds[1]=='') continue;
				$arr_insert['game_id'] = $game_id;
				$arr_insert['gins_key']= $hds[0];
				$arr_insert['gins_description']= trim($hds[1]);
				$this->db->insert("game_instruction",$arr_insert);
				}
			}
		}
	}
	 
	function fix_category() {
		$this->load->model('mcategory');
		$cates = $this->mcategory->gets();
		foreach($cates  as $cate)
		{
			$cat_code = '';
			if($cate->cat_parent >0 && $cate->cat_code =='khac'){
				$cat = $this->mcategory->get($cate->cat_parent,'cat_id');
				$cat_code =  $cat->cat_code.'-khac';
				$cat_name =  $cat->cat_name.' khác';
				$this->mcategory->update($cate->cat_id,'cat_id',array('cat_code'=>$cat_code,'cat_name'=>$cat_name, 'seo_title'=>$cat_name, 'seo_description'=>$cat_name, 'cat_description'=>$cat_name));
				echo "update: ".$cat->cat_name."<br>";
			}
		}
	}
	
	function get_image_not_exits(){
		$this->load->model('mgame');
		$games = $this->mgame->gets();
		echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
		$i= 1;
		foreach($games as $game){
			if(!file_exists($game->game_thumb)){
				echo $game->game_title."<br>";
				//echo $i.' - '.$game->game_title." | File: ".basename($game->game_thumb)."<br>";
				$i++;
			}
		
		}
	}
	function get_file_not_exits(){
		$this->load->model('mgame');
		$games = $this->mgame->gets();
		echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
		$i= 1;
		foreach($games as $game){
			if(!file_exists($game->game_file)){
				echo $game->game_title."<br>";
				//echo $i.' - '.$game->game_title." | File: ".basename($game->game_file)."<br>";
				$i++;
			}
		
		}
	}
	
	function rebuild(){
		$this->load->model('mrebuild');
	//	$this->mrebuild->rebuild_category_count();
		$this->mrebuild->rebuild_user_rank();
		
	}
	
	function fix_game_ins(){
		$this->load->model('mgameinstruction');
		$games = $this->mgameinstruction->gets();
		$new_key = '';
		foreach($games as $game){
			switch(strtolower($game->gins_key)){
				case 'cht':
					$new_key = 'MOUSE_LEFT';
				break;
			case 'ch':
					$new_key = 'MOUSE';
				break;
			case 'mt':
					$new_key = 'UP_DOWN_LEFT_RIGHT';
				break;
			case 'enter':
					$new_key = 'ENTER';
				break;
			case 'asdw':
					$new_key = 'ADSW';
				break;
			case 'space':
					$new_key = 'SPACE';
				break;
			case 'u1':
					$new_key = 'KEY_UP';
				break;
			case 'd1':
					$new_key = 'KEY_DOWN';
				break;
			case 'l1':
					$new_key = 'KEY_LEFT';
				break;
			case 'r1':
					$new_key = 'KEY_RIGHT';
				break;
			case 'lr':
					$new_key = 'LEFT_RIGHT';
				break;
			default:
					$new_key = strtoupper($game->gins_key);
				break;
			}
			$new_key = str_replace(",","-",$new_key);
			$this->mgameinstruction->update($game->gins_id,'gins_id',array('gins_key'=>$new_key));
		}
	}
	
	function gen_game_ins_key(){
		for($i=ord('0'); $i<ord ('Z'); $i++){
		//	echo chr($i) . "<br>";
			echo '$this->key_define[\''.chr($i).'\'] = \'['.strtoupper(chr($i)).']\';'."<br>";
		}
	}
	
	function test_rebuid_icache(){
		
		$this->load->model("mrebuild");
		$this->mrebuild->rebuid_game_image_cache();
		//$this->mrebuild->rebuid_user_avatar_cache();
		//$this->mrebuild->rebuid_game_file_rate();
	}
	function rebuid_game_image_cache($game_id =''){
		$this->load->model("mgame");
		$this->load->model("simage");
		$this->db->select('game_id, game_thumb,game_thumb_large');
		$games= $this->mgame->gets();
		if($games){
			foreach($games as $game){
				$this->simage->delete(@$game->game_thumb_large);
				$this->simage->cache(@$game->game_thumb_large);
				echo $game->game_id."\r";
			}
		}
	}
	function update_gname(){
		$this->load->model("mgame");
		$this->load->model("mloggamescores");
		$logs = $this->mloggamescores->gets(245,'log_gscores_id >');
		foreach($logs as $log){
			$this->mgame->update($log->game_id,'game_id',array(
				'game_key'=>$log->log_gscores_game_key,
			));
			echo "update gamekey: ".$log->game_id."<br>";
		}
	}
	
	function t(){
		$key = 'bánh mì sài gòn';
		$key = 'chiến tuyến phòng thủ';
		$key = 'Chiến tuyến phòng thủ 5';
		$code=  $this->sseo->seolink($key);
		echo $code;
	}
	
	function get_image_game24h(){
		$this->load->library('excel');
		$this->load->library('get_data_html');
		$this->load->model('mgame');
		$i = 0;
		$file = './dataupload/thumb285game.xlsx';
		//sleep(99999999999999);
		
		$inputFileType = PHPExcel_IOFactory::identify($file);
		$objReader = PHPExcel_IOFactory::createReader($inputFileType);
		$objPHPExcel = $objReader->load($file);
		$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
		$arr_insert = array();
		unset($sheetData[1]);
		echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
		foreach ($sheetData as $data) {
			$game = $this->mgame->get($data['A'],'game_id');
			if($game){
				$link = $data['E'];
				if($link !=''){
					$content = $this->get_data_html->get_content($link);
					$image = $this->get_data_html->GetBetween($content,'<meta itemprop="thumbnailUrl" name="og:image" content="','"');
					$current = $this->get_data_html->get_content($image);
					
					$ext = explode(".",basename($image));
					$ext = end($ext);
					$newName = $game->game_code.'-'.$game->game_id.''.'.'.$ext;
					
					file_put_contents('./dataupload/game/thumb/'.$newName, $current);
					
					$this->mgame->update($game->game_id,'game_id',array('game_thumb'=>'dataupload/game/thumb/'.$newName));
					
					echo "Thumb game ".$game->game_title." downloaded <br>";
				}
			}
		}
		
	}
	
	function update_thumb(){
		$this->load->model('mgame');
		$this->db->where("game_thumb_large",'');
		$games = $this->mgame->gets();
		foreach($games as $game){
			$ext = explode(".",$game->game_thumb);
			$ext = end($ext);
			$newName = $game->game_code.'-'.$game->game_id.'-large'.'.'.$ext;
			$newName = str_replace(basename($game->game_thumb), $newName,$game->game_thumb);
			copy($game->game_thumb,$newName);
			$this->mgame->update($game->game_id,'game_id',array('game_thumb_large'=>$newName));
			echo $game->game_title."<br>";
		}
		
	}
	
	function update_game_title(){
		$this->load->model('mgame');
		$games = $this->mgame->gets();
		foreach($games as $game){
			$arr_update = array();
			$arr_update['game_code'] = $this->sseo->seolink($game->game_title);
			$arr_update['seo_title'] = $game->game_title;
			$arr_update['seo_h1'] = $game->game_title;
			$this->mgame->update($game->game_id,'game_id',$arr_update);
			echo $game->game_title."<br>";
		}
		
	}
}
